﻿/* ==============================================================================
 * 功能描述：CharacterModule  
 * 
 * 创 建 者：郑镇泉
 * 
 * 创建日期：2016/4/7 16:11:01
 * ==============================================================================*/

using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using ZZQFrameWork;

#region 属性数据

/// <summary>
/// 基础属性类型
/// </summary>
public enum Enum_AttrType
{
    Liliang = 0, //力量
    Mingjie = 1, //敏捷
    Gengu = 2, //根骨
    Wuxing = 3, //悟性
    Meili = 4, //魅力
    Lixing = 5, //理性
    Ganxing = 6, //感性
    Danshi = 7, //胆识
    AtkAurum = 8, //金属性攻击
    AtkWood = 9, //木属性攻击
    AtkWater = 10, //水属性攻击
    AtkFire = 11, //火属性攻击
    AtkEarth = 12, //土属性攻击
    DefAurum = 13, //金属性防御
    DefWood = 14, //木属性防御
    DefWater = 15, //水属性防御
    DefFire = 16, //火属性防御
    DefEarth = 17, //土属性防御
    Count
}

/// <summary>
/// 基础属性数据
/// </summary>
public class AttrData
{
    /// <summary>
    /// 属性类型
    /// </summary>
    public Enum_AttrType attrType;

    /// <summary>
    /// 属性名称
    /// </summary>
    public string attrName;

    /// <summary>
    /// 属性值
    /// </summary>
    public int attrValue;

    public AttrData(Enum_AttrType type)
    {
        attrType = type;
        attrName = GetName(type);
        attrValue = 0;
    }

    public AttrData(Enum_AttrType type, int value)
    {
        attrType = type;
        attrName = GetName(type);
        attrValue = value;
        //Debug.Log("创建新属性，属性类型：" + attrName + "属性值：" + attrValue);
    }

    private string GetName(Enum_AttrType type)
    {
        string name = String.Empty;
        switch (type)
        {
            case Enum_AttrType.Wuxing:
                name = "悟性";
                break;
            case Enum_AttrType.Danshi:
                name = "胆识";
                break;
            case Enum_AttrType.Ganxing:
                name = "感性";
                break;
            case Enum_AttrType.Gengu:
                name = "根骨";
                break;
            case Enum_AttrType.Liliang:
                name = "力量";
                break;
            case Enum_AttrType.Lixing:
                name = "理性";
                break;
            case Enum_AttrType.Meili:
                name = "魅力";
                break;
            case Enum_AttrType.Mingjie:
                name = "敏捷";
                break;
            case Enum_AttrType.AtkAurum:
                name = "金攻";
                break;
            case Enum_AttrType.AtkWood:
                name = "木攻";
                break;
            case Enum_AttrType.AtkWater:
                name = "水攻";
                break;
            case Enum_AttrType.AtkFire:
                name = "火攻";
                break;
            case Enum_AttrType.AtkEarth:
                name = "土攻";
                break;
            case Enum_AttrType.DefAurum:
                name = "金防";
                break;
            case Enum_AttrType.DefWood:
                name = "木防";
                break;
            case Enum_AttrType.DefWater:
                name = "水防";
                break;
            case Enum_AttrType.DefFire:
                name = "火防";
                break;
            case Enum_AttrType.DefEarth:
                name = "土防";
                break;
        }
        return name;
    }
}

#endregion

#region 任务数据

/// <summary>
/// 任务类型
/// </summary>
public enum Enum_TaskType
{
    KillMonster, //杀怪
    GetGoods,//获取物品
    ReachedAttr//达到一定属性
}

/// <summary>
/// 任务条件数据
/// </summary>
public class TaskConditionData
{
    /// <summary>
    ///条件id
    /// </summary>
    public int conditionId;

    ///// <summary>
    ///// 任务类型
    ///// </summary>
    //public Enum_TaskType taskType;

    /// <summary>
    /// 需要数量
    /// </summary>
    public int needCount;

    /// <summary>
    /// 当前数量
    /// </summary>
    public int nowCount;

    public Enum_TaskProgress conditionProgress;

    public TaskConditionData(int id, int count)
    {
        conditionId = id;
        needCount = count;
        nowCount = 0;
        conditionProgress = Enum_TaskProgress.Unfinished;
    }
}

/// <summary>
/// 奖励物品类型
/// </summary>
public enum Enum_TaskRewardType
{
    Gold,//金币
    Exp,//经验
    Goods,//物品
    Equip,//装备
    PassLevel,//通关
}

/// <summary>
/// 奖励数据
/// </summary>
public class TaskRewardData
{
    /// <summary>
    /// 任务奖励类型
    /// </summary>
    public Enum_TaskRewardType rewardType;

    /// <summary>
    /// 奖励id
    /// </summary>
    public int rewardId;

    /// <summary>
    /// 奖励数量
    /// </summary>
    public int count;

    public TaskRewardData(Enum_TaskRewardType type, int count, int id = 0)
    {
        rewardType = type;
        this.rewardId = id;
        this.count = count;
    }
}

/// <summary>
/// 任务进度
/// </summary>
public enum Enum_TaskProgress
{
    /// <summary>
    /// 未完成
    /// </summary>
    Unfinished,

    /// <summary>
    /// 完成
    /// </summary>
    Finished,

    /// <summary>
    /// 交任务
    /// </summary>
    FinishToNpc
}

/// <summary>
/// 任务数据
/// </summary>
public class TaskData
{

    /// <summary>
    /// 任务id
    /// </summary>
    public int id;

    /// <summary>
    /// 任务名称
    /// </summary>
    public string name;

    /// <summary>
    /// 任务描述
    /// </summary>
    public string des;

    /// <summary>
    /// 任务类型
    /// </summary>
    public Enum_TaskType taskType;

    /// <summary>
    /// 任务进度
    /// </summary>
    public Enum_TaskProgress taskProgress;

    /// <summary>
    /// 任务条件集合
    /// </summary>
    public List<TaskConditionData> conditionDatList = new List<TaskConditionData>();

    /// <summary>
    /// 任务奖励集合
    /// </summary>
    public List<TaskRewardData> rewardDataList = new List<TaskRewardData>();

    public TaskData(int id)
    {
        TaskConfigTask task = TaskConfigProvider.Instance.GetTaskById(id);
        this.id = id;
        name = task.name;
        des = task.des;
        taskType = (Enum_TaskType) int.Parse(task.type);
        taskProgress = Enum_TaskProgress.Unfinished;
        for (int i = 0; i < task.condition.Length; i++)
        {
            TaskConfigTaskCondition condition = task.condition[i];
            TaskConditionData data = new TaskConditionData(int.Parse(condition.id), int.Parse(condition.count));
            conditionDatList.Add(data);
        }
        for (int i = 0; i < task.reward.Length; i++)
        {
            TaskConfigTaskReward reward = task.reward[i];
            TaskRewardData data = new TaskRewardData((Enum_TaskRewardType) int.Parse(reward.rewardType),
                int.Parse(reward.count), int.Parse(reward.id));
            rewardDataList.Add(data);
        }
    }

    /// <summary>
    /// 通过条件id获取条件数值
    /// </summary>
    /// <param name="conditionId"></param>
    /// <returns></returns>
    public TaskConditionData GetConditionById(int conditionId)
    {
        TaskConditionData data = conditionDatList.Find((obj) =>
        {
            return obj.conditionId == conditionId;
        });
        if (data == null) Debug.Log("没有找到该任务条件，id:" + conditionId);
        return data;
    }

    /// <summary>
    /// 添加任务条件需求，也就是更新任务进度
    /// </summary>
    /// <param name="conditionId"></param>
    /// <param name="count"></param>
    public void AddTaskConditionNeed(int conditionId, int count)
    {
        TaskConditionData data = GetConditionById(conditionId);
        data.nowCount += count;
        if (data.nowCount >= data.needCount)
        {
            //该条件完成，可以交任务
            Debug.Log("该条件已经完成");
            data.conditionProgress = Enum_TaskProgress.Finished;
        }
        if (CheckTaskFinished())
        {
            taskProgress = Enum_TaskProgress.Finished;
            ////通知任务完成
            TaskManager.Instance.OnFinishTask(this);
            //EventDispatcher.TriggerEvent(Events.TaskEvent.FinishTask, id);
        }
        else
        {
            EventDispatcher.TriggerEvent(Events.TaskEvent.UpdateTask, this);
        }
    }

    /// <summary>
    /// 检测任务是否已经完成
    /// </summary>
    /// <returns></returns>
    public bool CheckTaskFinished()
    {
        Debug.Log("这个任务有几个条件："+conditionDatList.Count);
        for (int i = 0; i < conditionDatList.Count; i++)
        {
            if (conditionDatList[i].conditionProgress == Enum_TaskProgress.Unfinished)
            {
                Debug.Log("当前条件id："+i+"未达成！");
                Debug.Log("该任务未完成！");
                return false;
            }
        }
        return true;
    }
}

#endregion

/// <summary>
/// 角色信息数据
/// </summary>
public class RoleDataVO
{
    public int id;//角色id
    public string name;//角色名
    public int lv;//等级
    public int exp;//当前经验
    public int maxExp;///升级需要经验
    public int hp;//血量
    public int maxHp;//最大血量
    public int mp;//内力
    public int maxMp;//最大内力
    public int streng;//体力
    public int maxStreng;//最大体力
    public int gold;//金钱
    public int minAtk;//最小攻击
    public int maxAtk;//最大攻击
    public int def;//防御
    public int magicAtk;//魔法攻击
    public float speed;//攻击速度
    public int attrPoint;//拥有的属性点
    public List<GoodsVO> equipList=new List<GoodsVO>(); //装备集合
    public List<SkillVO> skillList=new List<SkillVO>();//技能集合 
    public List<AttrData> attrDataList=new List<AttrData>()//基础属性集合
    {
        new AttrData(Enum_AttrType.Liliang),
        new AttrData(Enum_AttrType.Mingjie),
        new AttrData(Enum_AttrType.Gengu),
        new AttrData(Enum_AttrType.Danshi),
        new AttrData(Enum_AttrType.Meili),
        new AttrData(Enum_AttrType.Lixing ),
        new AttrData(Enum_AttrType.Ganxing),
        new AttrData(Enum_AttrType.Wuxing),
        new AttrData(Enum_AttrType.AtkAurum),
        new AttrData(Enum_AttrType.AtkWood),
        new AttrData(Enum_AttrType.AtkWater),
        new AttrData(Enum_AttrType.AtkFire),
        new AttrData(Enum_AttrType.AtkEarth),
        new AttrData(Enum_AttrType.DefAurum),
        new AttrData(Enum_AttrType.DefWood),
        new AttrData(Enum_AttrType.DefWater),
        new AttrData(Enum_AttrType.DefFire),
        new AttrData(Enum_AttrType.DefEarth)
    };

    public List<TaskData> taskDataList=new List<TaskData>();//已接任务集合 

    public RoleDataVO(int id,string name)
    {
        lv = 1;
        this.id = id;
        this.name = name;
        LevelConfigLevel level = LevelConfigProvider.Instance.GetLevelByLv(lv);
        maxHp = int.Parse(level.maxHp);
        maxMp = int.Parse(level.maxMp);
        maxExp = int.Parse(level.MaxExp);
        maxAtk = int.Parse(level.atk);
        magicAtk = int.Parse(level.magicAtk);
        def = int.Parse(level.def);
        speed = .5f;
        hp = maxHp;
        mp = maxMp;
        exp = 0;
        attrPoint = int.Parse(level.attrPoint);
    }

    #region 装备操作

    /// <summary>
    /// 根据装备id获取装备数据
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public GoodsVO GetEquipById(int id)
    {
        return equipList.Find(delegate(GoodsVO goods)
        {
            return goods.id == id;
        });
    }

    /// <summary>
    /// 根据装备类型获取装备数据
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public GoodsVO GetEquipByType(Enum_SubGoodsType type)
    {
        return equipList.Find(delegate(GoodsVO goods)
        {
            return goods.subGoodsType == type;
        });
    }

    /// <summary>
    /// 穿装备
    /// </summary>
    /// <param name="equip"></param>
    public void WearEquip(GoodsVO equip)
    {
        if(!CheckEquipIsFulfilRequirements(equip))return;//当不满足装备穿戴条件的时候，返回
        Debug.Log("需要查找是否有某个类型的装备，类型：" + equip.subGoodsType);
        GoodsVO goods = equipList.Find(delegate(GoodsVO obj)
        {
            return obj.subGoodsType == equip.subGoodsType;
        });
        //检测身上是否有该类型的装备，如果有则把身上的装备放到包裹里
        if (goods != null)
        {
            Debug.Log("需要换下的装备id：" + goods.id);
            ModuleManager.Instance.Get<BackpackModule>().AddGoods(goods);
            equipList.Remove(goods);
            maxAtk -= goods.attack;
            def -= goods.def;
            magicAtk -= goods.magicAttack;
        }
        //把要穿戴的装备穿到装备栏上

        GoodsVO vo = equip;
        equipList.Add(vo);
        maxAtk += vo.attack;
        def += vo.def;
        magicAtk += vo.magicAttack;
        EventDispatcher.TriggerEvent(Events.CharacterEvent.OnWearEquip, vo);
        ModuleManager.Instance.Get<BackpackModule>().RemoveGoods(equip);
        CalculateAttr();
    }

    /// <summary>
    /// 脱装备
    /// </summary>
    /// <param name="type"></param>
    public void DropEquip(Enum_SubGoodsType type)
    {
        GoodsVO goods = equipList.Find(delegate(GoodsVO obj)
        {
            return obj.subGoodsType == type;
        });
        if (goods != null)
        {
            ModuleManager.Instance.Get<BackpackModule>().AddGoods(goods);
            equipList.Remove(goods);
            EventDispatcher.TriggerEvent(Events.CharacterEvent.OnDropEquip, goods.subGoodsType);
        }
        CalculateAttr();
    }

    /// <summary>
    /// 穿上 && 脱下装备后重新计算属性
    /// </summary>
    private void CalculateAttr()
    {
        ClearAttrDataValue();//先清空数据，再重新计算
        //ClearMagicAttrDataValue();
        for (int i = 0; i < equipList.Count; i++)
        {
            GoodsVO equip = equipList[i];
            if (equip.attrDataList != null && equip.attrDataList.Count > 0)
            {
                for (int j = 0; j < equip.attrDataList.Count; j++)
                {
                    AttrData data = equip.attrDataList[j];
                    for (int k = 0; k < attrDataList.Count; k++)
                    {
                        if (attrDataList[k].attrType == data.attrType)
                        {
                            attrDataList[k].attrValue += data.attrValue;
                        }
                    }
                }
            }
        }
        //发送刷新角色信息面板事件
        EventDispatcher.TriggerEvent(Events.CharacterEvent.OnRefreshPlayerInfoPanel);
    }

    /// <summary>
    /// 把属性集合的所有值清零
    /// </summary>
    private void ClearAttrDataValue()
    {
        for (int i = 0; i < attrDataList.Count; i++)
        {
            attrDataList[i].attrValue = 0;
        }
    }

    /// <summary>
    /// 检查是否满足装备穿戴条件
    /// </summary>
    /// <param name="equip">需要穿戴的装备</param>
    /// <returns></returns>
    private bool CheckEquipIsFulfilRequirements(GoodsVO equip)
    {
        for (int i = 0; i < equip.requirementDataList.Count; i++)
        {
            RequirementData data = equip.requirementDataList[i];
            if (lv < data.lv)
            {
                Debug.Log("装备穿戴等级不足，需要等级："+lv);
                return false;
            }
            Enum_AttrType type = data.attr.attrType;
            if (GetAttrDataByAttrType(type).attrValue < data.attr.attrValue)
            {
                Debug.Log("不满足穿戴属性要求，属性：" + data.attr.attrName+"，需要值："+data.attr.attrValue);
                return false;
            }
        }
        return true;
    }

    /// <summary>
    /// 检查是否满足物品使用条件
    /// </summary>
    /// <param name="equip">需要穿戴的装备</param>
    /// <returns></returns>
    public bool CheckGoodsIsFulfilRequirements(GoodsVO goods)
    {
        for (int i = 0; i < goods.requirementDataList.Count; i++)
        {
            RequirementData data = goods.requirementDataList[i];
            if (lv < data.lv) return false;
            Enum_AttrType type = data.attr.attrType;
            if (GetAttrDataByAttrType(type).attrValue < data.attr.attrValue) return false;
        }
        return true;
    }

    #endregion

    #region 技能操作

    /// <summary>
    /// 学习技能
    /// </summary>
    /// <param name="skill"></param>
    /// <returns></returns>
    public bool LearnSkill(SkillVO skill)
    {
        if (skillList.Contains(skill) || attrPoint <= 0) return false; //如果已学习集合中存在该技能或者没有属性点则返回
        attrPoint--;
        skillList.Add(skill);
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnLearnSkill, skill, attrPoint); //发送学习技能事件
        return true;
    }

    #endregion

    #region 数据操作

    #region 升级后的新数据

    /// <summary>
    /// 获取升级所需经验
    /// </summary>
    /// <returns></returns>
    public int GetUpgradeExp()
    {
        //TODO 需从配置表调用数据
        return int.Parse(GetNewLevelInfo().MaxExp);
    }

    /// <summary>
    /// 获取最大hp
    /// </summary>
    /// <returns></returns>
    public int GetMaxHp()
    {
        //TODO 需从配置表调用数据
        return int.Parse(LevelConfigProvider.Instance.GetLevelByLv(lv).maxHp);
    }

    /// <summary>
    /// 获取最大mp
    /// </summary>
    /// <returns></returns>
    public int GetMaxMp()
    {
        //TODO 需从配置表调用数据
        return int.Parse(GetNewLevelInfo().maxMp);
    }

    /// <summary>
    /// 获取最大体力
    /// </summary>
    /// <returns></returns>
    public int GetMaxStreng()
    {
        //TODO 需从配置表调用数据
        return 100;
    }

    /// <summary>
    /// 获取需要增加的攻击力
    /// </summary>
    /// <returns></returns>
    public int GetNewLevelNeedAddAtk()
    {
        return int.Parse(GetNewLevelInfo().atk);
    }

    /// <summary>
    /// 获取需要增加的防御力
    /// </summary>
    /// <returns></returns>
    public int GetNewLevelNeedAddDef()
    {
        return int.Parse(GetNewLevelInfo().def);
    }

    /// <summary>
    /// 获取需要增加的魔法攻击力
    /// </summary>
    /// <returns></returns>
    public int GetNewLevelNeedAddMagicAtk()
    {
        return int.Parse(GetNewLevelInfo().atk);
    }

    /// <summary>
    /// 获取需要增加的属性点
    /// </summary>
    /// <returns></returns>
    public int GetNewLevelNeedAddAttrPoint()
    {
        return int.Parse(GetNewLevelInfo().attrPoint);
    }

    /// <summary>
    /// 获取新等级对应的level信息
    /// </summary>
    /// <returns></returns>
    LevelConfigLevel GetNewLevelInfo()
    {
        return LevelConfigProvider.Instance.GetLevelByLv(lv);
    }

    #endregion

    /// <summary>
    /// 增加经验
    /// </summary>
    /// <param name="exp"></param>
    public void AddExp(int exp)
    {
        this.exp += exp;
        if (this.exp >= maxExp)
        {
            this.exp -= maxExp;
            UpgradeLv();
        }
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateExp, this.exp, maxExp);
    }

    /// <summary>
    /// 升级
    /// </summary>
    /// <returns></returns>
    public bool UpgradeLv()
    {
        lv++;
        maxHp = GetMaxHp();
        maxMp = GetMaxMp();
        maxExp = GetUpgradeExp();
        maxStreng = GetMaxStreng();
        hp = maxHp;
        mp = maxMp;
        maxAtk += GetNewLevelNeedAddAtk();
        def += GetNewLevelNeedAddDef();
        magicAtk += GetNewLevelNeedAddMagicAtk();
        attrPoint += GetNewLevelNeedAddAttrPoint();
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateLv, lv);
        return true;
    }

    /// <summary>
    /// 恢复hp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverHp(int value)
    {
        if (hp == maxHp) return false;
        hp += value;
        if (hp > maxHp) hp = maxHp;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateHp, hp,maxHp);
        return true;
    }

    /// <summary>
    /// 减少Hp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductHp(int value)
    {
        hp -= value;
        hp=hp < 0 ? 0 : hp;
        Debug.Log("被怪物攻击了，hp:"+hp);
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateHp, hp,maxHp);
        if (hp <= 0)
        {
            //TODO 角色死亡,发送死亡事件
            hp = 0;
            EventDispatcher.TriggerEvent(Events.RoleEvent.OnRoleDeath);
            Debug.Log("角色死亡！");
        }
        return true;
    }

    /// <summary>
    /// 恢复mp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverMp(int value)
    {
        if (mp == maxMp) return false;
        mp += value;
        if (mp > maxMp) mp = maxMp;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateMp, mp,maxMp);
        return true;
    }

    /// <summary>
    /// 减少mp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductMp(int value)
    {
        if (mp < value) return false;
        mp -= value;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateMp, mp,maxMp);
        return true;
    }

    /// <summary>
    /// 恢复体力
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverStreng(int value)
    {
        if (streng == maxStreng) return false;
        streng += value;
        if (streng > maxStreng) streng = maxStreng;
        return true;
    }

    /// <summary>
    /// 减少体力
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductStreng(int value)
    {
        if (streng < value) return false;
        streng -= value;
        return true;
    }

    /// <summary>
    /// 添加金币
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool AddGold(int count)
    {
        gold += count;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateGold, gold);
        return true;
    }

    /// <summary>
    /// 扣除金币
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool DeductGold(int count)
    {
        if (gold < count) return false;
        gold -= count;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnUpdateGold, gold);
        return true;
    }

    /// <summary>
    /// 添加属性点
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool AddAttrPoint(int count)
    {
        attrPoint += count;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnAttrPointChanged, attrPoint);
        return true;
    }

    /// <summary>
    /// 扣除属性点
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool DeductAttrPoint(int count)
    {
        if (attrPoint < count) return false;
        streng -= count;
        EventDispatcher.TriggerEvent(Events.RoleEvent.OnAttrPointChanged, attrPoint);
        return true;
    }

    /// <summary>
    /// 根据属性类型获取角色该属性的属性数据
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public AttrData GetAttrDataByAttrType(Enum_AttrType type)
    {
        //Debug.Log("需要查找属性类型："+type);
        AttrData data = attrDataList.Find(delegate(AttrData obj)
        {
            return obj.attrType == type;
        });
        if (data != null)
        {
            return data;
        }
        return null;
    }

    /// <summary>
    /// 获取攻击力
    /// </summary>
    /// <returns></returns>
    public int GetAttack()
    {
        //todo 需要配置表配置攻击力计算公式
        int a = UnityEngine.Random.Range(minAtk,maxAtk+1);
        AttrData data = GetAttrDataByAttrType(Enum_AttrType.Mingjie);
        a += data.attrValue*2;
        Debug.Log("随机攻击力："+a);
        return a;
    }

    #endregion

    #region 任务操作

    /// <summary>
    /// 接任务
    /// </summary>
    /// <param name="taskId"></param>
    public void AcceptTask(int taskId)
    {
        TaskData task=new TaskData(taskId);
        AcceptTask(task);
    }

    public void AcceptTask(TaskData data)
    {
        taskDataList.Add(data);
        EventDispatcher.TriggerEvent(Events.TaskEvent.AcceptTask, data);
    }

    /// <summary>
    /// 更新任务
    /// </summary>
    /// <param name="taskId"></param>
    /// <param name="conditionId"></param>
    /// <param name="count"></param>
    public void UpdateTask(int taskId, int conditionId,int count)
    {
        TaskData task = GetTaskById(taskId);
        if (task == null)
        {
            Debug.Log("找不到这个任务，id:"+taskId);
            return;
        }
        task.AddTaskConditionNeed(conditionId,count);
        //EventDispatcher.TriggerEvent(Events.TaskEvent.UpdateTask,task);
    }

    /// <summary>
    /// 完成任务
    /// </summary>
    /// <param name="taskId"></param>
    public void FinishTaskToNpc(int taskId)
    {
        Debug.Log("交任务！");
        TaskData task = GetTaskById(taskId);
        if(!task.CheckTaskFinished())return;
        Debug.Log("任务条件都满足，开始获取奖励");
        //根据奖励不同增加奖励
        SetTaskFinishReward(task.rewardDataList);
       
        taskDataList.Remove(task);
        TaskManager.Instance.OnFinishTaskToNpc(taskId);
        EventDispatcher.TriggerEvent(Events.TaskEvent.FinishTaskToNpc, taskId);
    }

    /// <summary>
    /// 根据id获取任务
    /// </summary>
    /// <param name="taskId"></param>
    /// <returns></returns>
    public TaskData GetTaskById(int taskId)
    {
        TaskData task = taskDataList.Find((obj) =>
        {
            return obj.id == taskId;
        });
        return task;
    }

    /// <summary>
    /// 是否拥有某类型的任务
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public bool IsHasTaskTypeTask(Enum_TaskType type)
    {
        for (int i = 0; i < taskDataList.Count; i++)
        {
            if (taskDataList[i].taskType == type) return true;
        }
        return false;
    }

    public void CheckTaskHasUpdate(Enum_TaskType type, int conditionId, int count)
    {
        for (int i = 0; i < taskDataList.Count; i++)
        {
            if (taskDataList[i].taskType == type)
            {
                TaskData data = taskDataList[i];
                for (int j = 0; j < data.conditionDatList.Count; j++)
                {
                    if (data.conditionDatList[j].conditionId == conditionId)
                    {
                        UpdateTask(data.id,conditionId,count);
                        return;
                    }
                }
            }
        }
    }

    #endregion

    #region 奖励操作

    public void OnKillMonster(MonsterVO monster)
    {
        SetMonsterDrop(monster.dropDataList);
        if (!IsHasTaskTypeTask(Enum_TaskType.KillMonster))return;
        Debug.Log("有杀怪任务");
        CheckTaskHasUpdate(Enum_TaskType.KillMonster, monster.id,1);
    }

    public void GetGoods(GoodsVO goods)
    {
        if (!IsHasTaskTypeTask(Enum_TaskType.GetGoods)) return;
        Debug.Log("有物品任务");
        CheckTaskHasUpdate(Enum_TaskType.GetGoods, goods.id, 1);
    }

    /// <summary>
    /// 怪物死亡掉落
    /// </summary>
    /// <param name="data"></param>
    public void SetMonsterDrop(List<MonsterDropData> list)
    {
        foreach (MonsterDropData data in list)
        {
            //Debug.Log("奖励类型："+data.dropType);
            switch (data.dropType)
            {
                case Enum_MonsterDropType.Exp:
                    if(RandomSuccess(data.probability))
                    AddExp(data.count);
                    break;
                case Enum_MonsterDropType.Gold:
                    if (RandomSuccess(data.probability))
                AddGold(data.count);
                break;
                case Enum_MonsterDropType.Goods:
                if (!RandomSuccess(data.probability))break;
                for (int i = 0; i < data.count; i++)
                {
                    //Debug.Log(string.Format("掉落物品，id:{0},物品数量:{1},物品掉落概率:{2}",data.dropId,data.count,data.probability));
                    GetGoods(new GoodsVO(GoodsConfigProvider.Instance.GetGoodsById(data.dropId)));
                    ModuleManager.Instance.Get<BackpackModule>().AddGoods(new GoodsVO(GoodsConfigProvider.Instance.GetGoodsById(data.dropId)));
                }
                break;
                case Enum_MonsterDropType.Equip:
                if (!RandomSuccess(data.probability))break;
                for (int i = 0; i < data.count; i++)
                {
                    ModuleManager.Instance.Get<BackpackModule>().AddGoods(new GoodsVO(EquipConfigProvider.Instance.GetEquipById(data.dropId)));
                }
                break;
            }
        }
    }

    /// <summary>
    /// 任务完成奖励
    /// </summary>
    /// <param name="list"></param>
    public void SetTaskFinishReward(List<TaskRewardData> list)
    {
        foreach (TaskRewardData data in list)
        {
            switch (data.rewardType)
            {
                case Enum_TaskRewardType.Gold:
                    AddGold(data.count);
                    break;
                case Enum_TaskRewardType.Goods:
                    for (int i = 0; i < data.count; i++)
                    {
                        ModuleManager.Instance.Get<BackpackModule>().AddGoods(new GoodsVO(GoodsConfigProvider.Instance.GetGoodsById(data.rewardId)));
                    }
                    break;
                case Enum_TaskRewardType.Equip:
                    for (int i = 0; i < data.count; i++)
                    {
                        ModuleManager.Instance.Get<BackpackModule>().AddGoods(new GoodsVO(EquipConfigProvider.Instance.GetEquipById(data.rewardId)));
                    }
                    break;
            }
        }
    }

    /// <summary>
    /// 根据概率判断是否成功
    /// </summary>
    /// <param name="probability">概率</param>
    /// <returns></returns>
    private bool RandomSuccess(float probability)
    {
        float a = UnityEngine.Random.Range(0, 1f);
        if (a <= probability)
        {
            //Debug.Log("随机成功！：");
            return true;
        } 
        //Debug.Log("随机失败！：");
        return false;
    }

    #endregion

}

/// <summary>
/// 角色模块
/// </summary>
public class CharacterModule : BaseModule
{
    //当前主角色，多个角色或者有宝宝的时候可以用这个判断当前查看的角色
    public RoleDataVO mainRole;

    public CharacterModule()
    {
        AutoRegister = true;
        mainRole=new RoleDataVO(1002,"寂寞");
        //mainRole.UpgradeLv();
        //mainRole.hp = 70;
        //mainRole.mp = 30;
        //mainRole.exp = 123;
        //mainRole.maxHp = 125;
        //mainRole.maxExp = 200;
        //mainRole.maxMp = 50;
        //mainRole.gold = 3420;
        //mainRole.AddExp(1);
        //mainRole.GetAttrDataByAttrType(Enum_AttrType.Meili).attrValue = 23;
        //mainRole.GetMagicAttrDataByMagicAttrType(Enum_MagicAttrType.AtkFire).magicAttrValue = 3;
        //mainRole.maxAtk = 1225;
        //mainRole.def = 72;
        //mainRole.magicAtk = 51;
        //mainRole.hp = 23;
        //mainRole.maxHp = 100;
        //mainRole.mp = 45;
        //mainRole.maxMp = 50;
        //mainRole.streng = 92;
        //mainRole.maxStreng = 100;
    }

    #region 装备操作

    /// <summary>
    /// 穿装备
    /// </summary>
    /// <param name="equip"></param>
    public void WearEquip(GoodsVO equip)
    {
        mainRole.WearEquip(equip);
    }

    /// <summary>
    /// 脱装备
    /// </summary>
    /// <param name="type"></param>
    public void DropEquip(Enum_SubGoodsType type)
    {
        mainRole.DropEquip(type);
    }

    #endregion

    #region 技能操作

    /// <summary>
    /// 学习技能
    /// </summary>
    /// <param name="skill"></param>
    /// <returns></returns>
    public bool LearnSkill(SkillVO skill)
    {
        return mainRole.LearnSkill(skill);
    }

    #endregion

    #region 数据操作

    /// <summary>
    /// 升级
    /// </summary>
    /// <returns></returns>
    public bool UpgradeLv()
    {
        return mainRole.UpgradeLv();
    }

    /// <summary>
    /// 恢复hp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverHp(int value)
    {
        return mainRole.RecoverHp(value);
    }

    /// <summary>
    /// 减少Hp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductHp(int value)
    {
        return mainRole.DeductHp(value);
    }

    /// <summary>
    /// 恢复mp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverMp(int value)
    {
        return mainRole.RecoverMp(value);
    }

    /// <summary>
    /// 减少mp
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductMp(int value)
    {
        return mainRole.DeductMp(value);
    }

    /// <summary>
    /// 恢复体力
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool RecoverStreng(int value)
    {
        return mainRole.RecoverStreng(value);
    }

    /// <summary>
    /// 减少体力
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public bool DeductStreng(int value)
    {
        return mainRole.DeductStreng(value);
    }

    /// <summary>
    /// 添加金币
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool AddGold(int count)
    {
        return mainRole.AddGold(count);
    }

    /// <summary>
    /// 扣除金币
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool DeductGold(int count)
    {
        return mainRole.DeductGold(count);
    }

    /// <summary>
    /// 添加属性点
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool AddAttrPoint(int count)
    {
        return mainRole.AddAttrPoint(count);
    }

    /// <summary>
    /// 扣除属性点
    /// </summary>
    /// <param name="count"></param>
    /// <returns></returns>
    public bool DeductAttrPoint(int count)
    {
        return mainRole.DeductAttrPoint(count);
    }
    #endregion

    #region 任务操作

    /// <summary>
    /// 接任务
    /// </summary>
    /// <param name="taskId"></param>
    public void AcceptTask(int taskId)
    {
       mainRole.AcceptTask(taskId);
    }

    /// <summary>
    /// 更新任务
    /// </summary>
    /// <param name="taskId"></param>
    /// <param name="conditionId"></param>
    /// <param name="count"></param>
    public void UpdateTask(int taskId, int conditionId, int count)
    {
       mainRole.UpdateTask(taskId,conditionId,count);
    }

    /// <summary>
    /// 完成任务
    /// </summary>
    /// <param name="taskId"></param>
    public void FinishTaskToNpc(int taskId)
    {
      mainRole.FinishTaskToNpc(taskId);
    }

    /// <summary>
    /// 根据id获取任务
    /// </summary>
    /// <param name="taskId"></param>
    /// <returns></returns>
    public TaskData GetTaskById(int taskId)
    {
        return mainRole.GetTaskById(taskId);
    }

    #endregion

}